package com.ciwong.epaper.modules.me.ui.clazz;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.bean.SelectObject;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.me.adapter.ClassMemberAdapter;
import com.ciwong.epaper.modules.me.bean.ClassMember;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.Member;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.LogOutUtil;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.widget.GradeSelectDialog;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.Blur;
import com.ciwong.mobilelib.widget.TitleBar;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.io.Serializable;
import java.util.List;

/**
 * Created by neo on 2016/7/1.
 */
public class ClassDetailActivity   extends BaseActivity  implements View.OnClickListener{

    private ImageView iv_class_avatar;
    private  ImageView iv_class_avatar_bg;
    private  TextView tv_class_name;
    private  TextView tv_teacher_phone_number;
    private  TextView tv_teacher_name;
    private  TextView tv_class_member_count;
    private  TextView tv_school_name;
    private  TextView tv_grade;
    private  View handle_teacher_number;
    private  View handle_teacher_name;
    private  View handle_iv_class_member_avatar;
    private GridView gv_class_member;
    private Clazz mClazz;
    private Button btn_change_class;
    private ClassMemberAdapter mClassMemberAdapter;
//    private TitleBar app_title_bar;
    private Activity mActivity;

    @Override
    protected void preCreate()
    {
        super.preCreate();
        mClazz = (Clazz) getIntent()
                .getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
    }


    @Override
    protected int setView( ) {
        return R.layout.activity_class_detail;
    }

    @Override
    protected void findViews( ) {

        iv_class_avatar = (ImageView) findViewById(R.id.iv_class_avatar);
        tv_class_name = (TextView) findViewById(R.id.tv_class_name);
        tv_teacher_phone_number = (TextView) findViewById(R.id.tv_teacher_phone_number);
        tv_teacher_name = (TextView) findViewById(R.id.tv_teacher_name);
        tv_class_member_count = (TextView) findViewById(R.id.tv_class_member_count);
        tv_school_name = (TextView) findViewById(R.id.tv_school_name);
        tv_grade = (TextView) findViewById(R.id.tv_grade);
        btn_change_class = (Button) findViewById(R.id.btn_change_class);
        handle_teacher_number = findViewById(R.id.handle_teacher_number);
        handle_teacher_name = findViewById(R.id.handle_teacher_name);
        handle_iv_class_member_avatar = findViewById(R.id.handle_iv_class_member_avatar);
        gv_class_member = (GridView) findViewById(R.id.gv_class_member);
//        app_title_bar = (TitleBar) findViewById(R.id.app_title_bar);

        iv_class_avatar_bg = (ImageView) findViewById(R.id.iv_class_avatar_bg);

    }

    @Override
    protected void initEvent() {
        btn_change_class.setOnClickListener(this);
        findViewById(R.id.btn_class_member).setOnClickListener(this);
        gv_class_member.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MeJumpManager.jumpToClassMember(ClassDetailActivity.this, R.string.go_back,mClazz);
            }
        });
    }

    @Override
    protected void init() {

        mActivity=this;
        if (null != mClazz) {
            mClassMemberAdapter = new ClassMemberAdapter(this,ClassMemberAdapter.PAGE_TYPE_CLASS_DETAIL);
            gv_class_member.setAdapter(mClassMemberAdapter);
        }

        //不用默认的标题栏，为了头部背景模糊化
        hideTitleBar();

        findViewById(R.id.btn_exit_page).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();

            }
        });

    }

    @Override
    protected void loadData() {

        if (null != mClazz) {

            //班级名字在这里刷新了，因为新老接口问题导致列表班级别名，到取详情的时候变成别名了
            tv_class_name.setText(mClazz.getClassName());

            getNetClassDetail(mClazz);
            getNetClassList(mClazz);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EpaperConstant.REQUEST_CODE_CHANGE_CLASS_PAGE:
                    setResult(RESULT_OK);
                    finish();
                    break;
            }
        }
    }



    private ImageLoadingListener imageLoadListener = new ImageLoadingListener()
    {
        @Override
        public void onLoadingStarted(String s, View view)
        {
        }

        @Override
        public void onLoadingFailed(String s, View o, FailReason failReason)
        {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) mActivity
                    .getResources().getDrawable(R.drawable.about_icon);
            setHeadBrRl(bitmapDrawable.getBitmap());
        }

        @Override
        public void onLoadingComplete(String s, View o, Bitmap bitmap)
        {
            if (bitmap == null)
            {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) mActivity
                        .getResources().getDrawable(R.drawable.about_icon);
                bitmap = bitmapDrawable.getBitmap();
            }
            setHeadBrRl(bitmap);
        }

        @Override
        public void onLoadingCancelled(String s, View view)
        {
        }

    };

    /**
     * 设置模糊头像背景图
     *
     * @param headBitmap
     */
    private void setHeadBrRl(Bitmap headBitmap)
    {
        int radius = 8;
        final Bitmap blurBitmap = Blur.fastblur(this, headBitmap, radius);
        iv_class_avatar_bg.setImageBitmap(blurBitmap);
    }

    /**
     * 获取网络班级列表
     */
    private void getNetClassDetail(Clazz clazz)
    {
        MeDao.getInstance().getClassDetail(EApplication.BRAND_ID,clazz.getId(), new BaseExtCallBack(ClassDetailActivity.this, EApplication.getInstance().getUserInfoBase().getUserId()+"")
        {

            @Override
            public void success(Object data)
            {
                mClazz= (Clazz) data;
                refreshUI(mClazz);
                // 更新本地班级列表
//                SerializableManager.getInstance().serialize(
//                        SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST,
//                        (Serializable) clazzs);
//                hideMiddleProgressBar( );
            }

            @Override
            public void failed(int errorCode, Object data)
            {
                super.failed(errorCode, data);
                hideMiddleProgressBar();

            }

            @Override
            public void failed(Object data)
            {
                hideMiddleProgressBar();
            }
        });


    }

    /**
     * 获取网络班级成员列表
     */
    private void getNetClassList(Clazz  clazz)
    {
        showCricleProgress();
        MeDao.getInstance().getClassMember(EApplication.BRAND_ID,clazz.getId(),1, 1,new BaseExtCallBack(ClassDetailActivity.this, EApplication.getInstance().getUserInfoBase().getUserId()+"")
        {

            @Override
            public void success(Object data)
            {
                List<ClassMember> users = (List<ClassMember>) data;
                // 更新本地班级列表

                if (null != users && users.size() > 0) {

                    tv_class_member_count.setText(users.size()+"");
                    mClassMemberAdapter.clear();
                    mClassMemberAdapter.addAll(users);

                }

                hideCricleProgress( );

                CWLog.d("ciwong", "#######users.size()#########"+users.size());
            }

            @Override
            public void failed(int errorCode, Object data)
            {
                super.failed(errorCode, data);
                hideCricleProgress( );
            }

            @Override
            public void failed(Object data)
            {
                hideCricleProgress();
            }
        });
    }


    /**
     * 刷新界面
     *
     * @param clazz
     *            班级信息集
     */
    private void refreshUI(Clazz clazz)
    {
        if (clazz != null )
        {
            //班级名字不在这里刷新了，因为新老接口问题导致列表班级别名，到取详情的时候变成别名了
//            tv_class_name.setText(mClazz.getClassName());
//            tv_teacher_phone_number.setText(mClazz.getClassMemberNum()+"");
//            tv_teacher_name.setText(mClazz.getRoomUserName());
            if(mClazz.getMember() != null && mClazz.getMember().size()>0)
            {
                handle_iv_class_member_avatar.setVisibility(View.VISIBLE);
                //人数不包括老师
//                tv_class_member_count.setText(mClazz.getMember().size()+"");
                List<Member> memberList=mClazz.getMember();
                boolean disPlayManagerInfo=false;
                Member managerMem=null;

                for (Member member : memberList) {
                    if (member.getRote() == EpaperConstant.USER_ROLE_TEACHER && member.getIsAdmin() == 1) {
                        disPlayManagerInfo=true;
                        managerMem=member;
                        break;
                    }
                }


                if (disPlayManagerInfo) {
                    handle_teacher_number.setVisibility(View.VISIBLE);
                    handle_teacher_name.setVisibility(View.VISIBLE);
                    if (managerMem != null) {
                        tv_teacher_name.setText(managerMem.getUserName());
//                        tv_teacher_name.setText(mClazz.getRoomUserName());

                        if (managerMem.getMobile() != null && !managerMem.getMobile().equals("")) {
                            tv_teacher_phone_number.setText(managerMem.getMobile());
                        }else {
                            tv_teacher_phone_number.setText("无");
                        }
                    }
                }else
                {
                    handle_teacher_number.setVisibility(View.GONE);
                    handle_teacher_name.setVisibility(View.GONE);
                }

            }else {
                handle_iv_class_member_avatar.setVisibility(View.GONE);
            }
            tv_school_name.setText(mClazz.getSchool().getSchoolName());
            tv_grade.setText(GradeSelectDialog.getGradeNameById(mClazz.getGradeId()));

            String classAvatar = mClazz.getClassAvatar();
            classAvatar = TextUtils.isEmpty(classAvatar) ? "drawable://" + R.drawable.about_icon
                    : classAvatar;
            ImageLoader.getInstance().displayImage(classAvatar, iv_class_avatar,
                    EConstants.getDefAvatarCircleBuilder(), imageLoadListener);
        }

//        SerializableManager.getInstance().serialize(
//                SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT,
//                clazz);

    }

    @Override
    public void onClick(View v) {
        int id=v.getId();

        if (id == R.id.btn_change_class) {
            MeJumpManager.jumpToChangeClass(ClassDetailActivity.this, R.string.go_back, IntentValue.JumpToJoinClassType.TYPE_CHANGE_CLASS,EpaperConstant.REQUEST_CODE_CHANGE_CLASS_PAGE,mClazz);
        } else if (id == R.id.btn_class_member ) {
            MeJumpManager.jumpToClassMember(ClassDetailActivity.this, R.string.go_back,mClazz);
        }

    }
}
